package xyz.pro5books.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xyz.pro5books.mapper.*;
import xyz.pro5books.pojo.*;
import xyz.pro5books.vo.PageResult;
import xyz.pro5books.vo.PageResult2;
import xyz.pro5books.vo.UserCollBook;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BookCatMapper bookCatMapper;

    @Autowired
    private UserCollMapper userCollMapper;

    @Autowired
    private MsgMapper msgMapper;

    @Autowired
    private BookReportMapper bookReportMapper;

    @Autowired
    private BookPicMapper bookPicMapper;

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    @Transactional
    public void addDownloadNum(Integer bookId, Integer downNum) {
        Book book = new Book();
        book.setId(bookId)
                .setDownNum(downNum);
        System.out.println(downNum);
        bookMapper.updateById(book);
    }

    @Override
    public Book getBookById(Integer id) {
        return bookMapper.selectById(id);
    }

    @Override
    public void addCollections(Integer userId, Integer bookId) {
        UserColl userColl = new UserColl();
        userColl.setBookId(bookId)
                .setUserId(userId);
        System.out.println(userColl);
        userCollMapper.insert(userColl);
    }

    @Override
    public Integer getUserCollNum(Integer userId) {
        QueryWrapper<UserColl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return userCollMapper.selectCount(queryWrapper);
    }

    @Override
    public void concelCollect(Integer userId, Integer bookId) {
        QueryWrapper<UserColl> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId)
                .eq("book_id",bookId);
        userCollMapper.delete(queryWrapper);
    }

    @Override
    public Integer getBookCollectState(Integer userId, Integer bookId) {
        QueryWrapper<UserColl> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId)
                .eq("book_id",bookId);
        List<UserColl> userColls = userCollMapper.selectList(queryWrapper);
        System.out.println("BookServiceImpl.getBookCollectState"+userColls);
        if (userColls.isEmpty()){
            System.out.println("userstate = " + 0);
            return 0;
        }else {
            System.out.println("userstate = " + 1);
            return 1;
        }
    }

    @Override
    public void doReport(Integer userId, Integer bookId, Integer reason) {
        Book book = bookMapper.selectById(bookId);
        String msgContent = "ID为 "+bookId+" 、名为 《"+book.getName()+"》 的书籍被举报，请尽快处理。";
        Msg msg = new Msg();
        msg.setSend(userId)
                .setRece(1)
                .setMessage(msgContent)
                .setTime(new Date());
        msgMapper.insert(msg);

        BookReport bookReport = new BookReport();
        bookReport.setUserId(userId)
                .setBookId(bookId)
                .setReason(reason);
        System.out.println("BookServiceImpl.doReport"+bookReport);
        bookReportMapper.insert(bookReport);
    }

    @Override
    public void concelReport(Integer userId, Integer bookId) {
        QueryWrapper<BookReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId)
                .eq("book_id",bookId);
        bookReportMapper.delete(queryWrapper);

        String msgStr = "ID为 "+bookId+" 的";
        QueryWrapper<Msg> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("send",userId)
                .like("message",msgStr);
        msgMapper.delete(queryWrapper1);
    }

    @Override
    public Integer getBookReportState(Integer userId, Integer bookId) {
        QueryWrapper<BookReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("book_id", bookId);
        List<BookReport> bookReports = bookReportMapper.selectList(queryWrapper);
        if (bookReports.isEmpty()){
            return 0;
        }else {
            return 1;
        }
    }

    @Override
    public List<String> getBookPic(Integer bookId) {
        QueryWrapper<BookPic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        List<BookPic> bookPics = bookPicMapper.selectList(queryWrapper);
        List<String> bookPicAddrs = new ArrayList<>();
        for (BookPic bookpic : bookPics){
            bookPicAddrs.add(bookpic.getBookPicAddr());
        }
        System.out.println("bookPicAddrs = " + bookPicAddrs);
        return bookPicAddrs;
    }

    @Override
    @Transactional
    public PageResult2 searchall(PageResult2 pageResult2) {
        IPage iPage = new Page(pageResult2.getPageNum(),pageResult2.getPageSize());
        Boolean queBoo = StringUtils.hasLength(pageResult2.getQuery());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);
        if (pageResult2.getSearchQueryType() == 1){
            queryWrapper.like(queBoo, "name", pageResult2.getQuery());
        }else if (pageResult2.getSearchQueryType() == 2){
            queryWrapper.likeRight("stage",pageResult2.getQuery());
        }
        if (pageResult2.getOrderQueryType() == 1){
            queryWrapper.orderByDesc("rate");
            System.out.printf("rate");
        }else if (pageResult2.getOrderQueryType() == 2){
            queryWrapper.orderByDesc("down_num");
            System.out.printf("down_num");
        }else if (pageResult2.getOrderQueryType() == 3){
            queryWrapper.orderByDesc("updated");
            System.out.printf("updated");
        }
        IPage iPage1 = bookMapper.selectPage(iPage,queryWrapper);
        pageResult2.setRows(iPage1.getRecords());
        pageResult2.setTotal(iPage1.getTotal());
        return pageResult2;
    }

    @Override
    @Transactional
    public List<BookCat> getmenulist() {
        QueryWrapper<BookCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0)
                .orderByAsc("stage_id");
        List<BookCat> menuOneList = bookCatMapper.selectList(queryWrapper);
        for(BookCat menuOne : menuOneList){
            queryWrapper.clear();
            queryWrapper.eq("parent_id", menuOne.getId())
                    .orderByAsc("stage_id");
            menuOne.setChildren(bookCatMapper.selectList(queryWrapper));
            for (BookCat menuTwo : menuOne.getChildren()){
                queryWrapper.clear();
                queryWrapper.eq("parent_id", menuTwo.getId())
                        .orderByAsc("stage_id");
                menuTwo.setChildren(bookCatMapper.selectList(queryWrapper));
            }
        }
        return menuOneList;
    }


    @Override
    public PageResult getBookList(PageResult pageResult) {
        //1.定义MP分页对象，arg1页数，arg2行数
        IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        //2.构建查询条件构造器
        QueryWrapper queryWrapper =new QueryWrapper();
        //判断用户的数据是否有效，有效true,无效false
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "name", pageResult.getQuery());
        //经过MP的分页查询，将所有的分页数(total/结果/页数/条数/xxx)据封装到Ipage对象中
        iPage = bookMapper.selectPage(iPage,queryWrapper);
        //从分页对象中获取分页后的总记录数
        long total = iPage.getTotal();
        //从分页对象中获取分页后的结果
        List<User> rows = iPage.getRecords();

        //String online = rows.getOnline();
        return pageResult.setTotal(total).setRows(rows);
    }
    //修改图书状态
    @Override
    @Transactional
    public void updateBookStatus(Book book) {
        bookMapper.updateById(book);

    }
    //删除书籍
    @Override
    @Transactional
    public void deleteBook(Integer id) {
        bookMapper.deleteById(id);
    }
    //获取要修改的图书信息
    @Override
    public Book getBook(Integer id) {
        Book book = bookMapper.selectById(id);
        return book;
    }

    @Override
    @Transactional
    public void updateBook(Book book) {
        bookMapper.updateById(book);
    }

    //书籍上传数量统计
    @Override
    public List selBookCount() {
        List list = bookMapper.selBookCount();
        return list;

    }

    @Override
    public void addBookForm(Book book) {
        bookMapper.insert(book);
    }

    @Override
    public List<UserCollBook> getCollList(Integer userId) {
        List<UserCollBook> userCollBookList = new ArrayList<>();

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        List<UserColl> userCollList = userCollMapper.selectList(queryWrapper);
        for (UserColl userColl : userCollList){
            Book book = bookMapper.selectById(userColl.getBookId());
            userCollBookList.add(new UserCollBook().setName(book.getName())
                                .setAuthor(book.getAuthor())
                                .setPrice(book.getPrice())
                                .setCollTime(userColl.getUpdated())
                                .setId(userColl.getBookId())
            );
        }
        System.out.println("userCollList = " + userCollList);
        System.out.println("bookList = " + userCollBookList);
        return userCollBookList;
    }

    @Override
    public PaymentInfo getPaymentInfo(String token) {
        if(token.length() > 0){
            return paymentInfoMapper.selectById(1);
        }else {
            return null;
        }
    }
}
